package drds.plus.sql_process.optimizer.chooser.share_delegate;

import drds.plus.sql_process.abstract_syntax_tree.node.Node;
import drds.plus.sql_process.abstract_syntax_tree.node.query.TableQuery;
import drds.plus.sql_process.optimizer.OptimizerException;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

class ShareDelegateMethodInterceptor implements MethodInterceptor {

    private ShareDelegate shareDelegate;

    public ShareDelegateMethodInterceptor(ShareDelegate shareDelegate) {
        this.shareDelegate = shareDelegate;
    }

    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Node node = (Node) object;
        String name = method.getName();
        if (name.equals("getDataNodeId")) {
            return node.getDataNodeId(shareDelegate.shareIndex);
        } else if (name.equals("setDataNodeId")) {
            node.setDataNodeId(shareDelegate.shareIndex, (String) args[0]);
            return node;
        } else if (name.equals("setExtra")) {
            node.setExtra(shareDelegate.shareIndex, args[0]);
            return node;
        } else if (name.equals("getExtra")) {
            return node.getExtra(shareDelegate.shareIndex);
        } else if (name.equals("toExecutePlan")) {
            return node.toExecutePlan(shareDelegate.shareIndex);
        } else if (name.equals("setActualTableName")) {
            ((TableQuery) node).setActualTableName(shareDelegate.shareIndex, (String) args[0]);
            return node;
        } else if (name.equals("getActualTableName")) {
            return ((TableQuery) node).getActualTableName(shareDelegate.shareIndex);
        } else {
            throw new OptimizerException("impossible proxy method : " + name);
        }

    }

}
